package com.tgm.service.impl;
import com.github.pagehelper.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.tgm.domain.common.PageResult;
import com.tgm.domain.entity.UserInfo;
import com.tgm.domain.vo.ConsumptionShowVO;
import com.tgm.domain.vo.PortraitVO;
import com.tgm.mapper.ConsumptionRecordMapper;
import com.tgm.mapper.UserInfoMapper;
import com.tgm.service.UserInfoService;
import com.tgm.utils.ConsumptionDataConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户信息表(UserInfo)表服务实现类
 *
 * @author makejava
 * @since 2025-10-20 20:59:32
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private ConsumptionRecordMapper consumptionRecordMapper;
    @Autowired
    private ConsumptionDataConverter consumptionDataConverter;

    /**
     * 获取用户消费数据
     * @param userId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public String getUserConsumptionText(String userId, String startTime, String endTime) {
        //查出用户的消费记录
        List<PortraitVO> portraitVOS = consumptionRecordMapper.selectByUserIdAndTime(userId, startTime, endTime);
        //转为AI易理解的文本
        String s = consumptionDataConverter.convertUserConsumptionToText(userId, portraitVOS);
        System.out.println(s);
        return s;
    }


    /**
     * 获取群体特征
     * @param department
     * @param grade
     * @return
     */
    @Override
    public String getGruopFeatures(String department, String grade) {
        //查出该学院或者该年级的消费特征
        List<PortraitVO> portraitVOS = consumptionRecordMapper.selectByDepOrGrade(department, grade);
        String s = consumptionDataConverter.convertUserConsumptionToText(department, grade, portraitVOS);
        System.out.println(s);
        return s;
    }

    /**
     * 分页查询
     * @param pageNum
     * @param keyword
     * @return
     */
    @Override
    public PageResult<UserInfo> page(Integer pageNum,String  keyword) {
        if (pageNum == null){
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, 10);
        List<UserInfo> list = null;
        if(keyword != null){
            list = query().eq("user_name", keyword).or().eq("user_id", keyword).list();
        } else {
            list = list(); // 只有在没有关键字时才执行默认查询
        }
// 确保 list 是 Page 类型，如果不是则创建一个新的 Page 对象
        Page<UserInfo> p;
        if (list instanceof Page) {
            p = (Page<UserInfo>) list;
        } else {
            // 如果不是 Page 对象，创建一个包装对象
            Page<UserInfo> page = new Page<>();
            page.addAll(list);
            page.setTotal(list.size());
            p = page;
        }
        return new PageResult<>(p.getTotal(), p.getResult());

    }
}

